package com.yuda.tools.downloadanswer.controller;

import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.tools.downloadanswer.dto.PaperSubject;
import com.yuda.tools.downloadanswer.fegin.RemoteCheckAnswerService;
import com.yuda.tools.downloadanswer.service.DownLoadAnswerService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@RestController
public class DownLoadAnswer extends BaseController {


    @Autowired
    private DownLoadAnswerService downLoadAnswerService;

    @Autowired
    private RemoteCheckAnswerService remoteCheckAnswerService;

    private final AtomicBoolean canUnionFormalAnswer = new AtomicBoolean(true);

    private final AtomicBoolean canCleanRedundantMq = new AtomicBoolean(true);

    private final AtomicBoolean updateAnswerFromMq = new AtomicBoolean(true);

    private final AtomicBoolean canDownLoadLog = new AtomicBoolean(true);


    @PostMapping("/saveAnswer/{testSession}/{subjectIndex}")
    public synchronized AjaxResult saveAnswer(@PathVariable("testSession") int testSession,
                                              @PathVariable("subjectIndex") int subjectIndex) {
        try {
            boolean flag = downLoadAnswerService.checkCanRun();
            System.out.println(flag ? "可以运行" : "不可以运行");
            if (flag) {

                //判断是否有待处理的
                //----2021 年11月26 修改，暂时注释，以后打开
//                TableDataInfo tableDataInfo = remoteCheckAnswerService.list(null, null, 1, 1);
//                if (tableDataInfo.getCode() == 200) {
//                    boolean empty = tableDataInfo.getRows().isEmpty();
//                    if (!empty) { //说明了 有 标记待处理的
//                        return AjaxResult.error("需要先把已标记待处理的处理完毕");
//                    }
//                }
                //----2021 年11月26 修改，暂时注释，以后打开
                downLoadAnswerService.saveAnswer(testSession, subjectIndex);

            } else {
                return AjaxResult.success(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(1);
    }


    @GetMapping("/downLoadAnswerList")
    public TableDataInfo downLoadAnswerList() {

        List<PaperSubject> list = downLoadAnswerService.downLoadAnswerList();
        return getDataTable(list);
    }


    /**
     * 获取当前正在进行的任务的进度
     *
     * @return
     */
    @GetMapping("/getDownLoadProgress")
    public AjaxResult getDownLoadProgress() {
        String progress = downLoadAnswerService.getDownLoadProgress();
        return AjaxResult.success(progress);
    }

    @Deprecated
//    @ApiOperation("点击一键合并的时候可以调用此接口来判断目前正在执行的阶段 有三个阶段 第一创建表 第二处理数据，第三取数据")
//    @GetMapping("/getAssemblyDataTips")
    public AjaxResult getAssemblyDataTips() {
        return AjaxResult.success(downLoadAnswerService.getUnAssemblyDataTip());
    }

    /**
     * 一键合并查询列表
     */
    @Deprecated
//    @ApiOperation("点击一键合并按钮调用此接口获取列表的数据，注意第一次调用非常慢")
//    @ApiOperation("此接口已废弃请勿使用，后边会移除")
//    @GetMapping("/unAssemblyData")
    public AjaxResult unAssemblyData() {
        return AjaxResult.success(downLoadAnswerService.unAssemblyData());
    }

    @ApiOperation("一键操作之第 1 步 合并数据 这一步可能会超时")
    @GetMapping("/unionFormalAnswer")
    public AjaxResult unionFormalAnswer() {

        if (canUnionFormalAnswer.get()) {
            canUnionFormalAnswer.set(false);
            try {
                downLoadAnswerService.unionFormalAnswer();
            } catch (Exception e) {
                return AjaxResult.error("系统报错了");
            } finally {
                canUnionFormalAnswer.set(true);
            }
        } else {
            return AjaxResult.error("有任务在执行请稍等");
        }
        return AjaxResult.success("执行成功");
    }

    @ApiOperation("一键操作 第2.0步 mq相关操作 这一步可能会超时")
    @GetMapping("/cleanRedundantMq")
    public AjaxResult cleanRedundantMq() {

        if (canCleanRedundantMq.get()) {
            canCleanRedundantMq.set(false);
            try {
                //1.判断mq 去重表是否存在
                int num = downLoadAnswerService.determineWhetherTableNeedsToBeCreated();
                if (num > 0) {
                    //判断mq 去重表是否有记录 如果有记录 提醒清理
                    int records = downLoadAnswerService.hasAnyRecords();
                    if (records > 0) {
                        return AjaxResult.success("needCleanMq");
                    }
                }

                if (num == 0) {
                    downLoadAnswerService.createTableNamedMqQc();//创建mq 去重表
                }

                //mq 去重并且 保存到去重表
                try {
                    downLoadAnswerService.executeCleanRedundantMq();
                    return AjaxResult.success("去重成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                canCleanRedundantMq.set(true);
            }
        } else {
            return AjaxResult.error("有程序正在运行");
        }
        return AjaxResult.success("执行完成");
    }

    @ApiOperation("获取是否完成 unionFormalAnswer 接口传1  CleanRedundantMq 接口传2 updateAnswerFromMq 接口传4")
    @GetMapping("/getStepStatus/{step}")
    public AjaxResult getStepTwoStatus(@PathVariable("step") Integer step) {

        if (step == 1) {
            return AjaxResult.success(canUnionFormalAnswer.get());
        }

        if (step == 2) {
            return AjaxResult.success(canCleanRedundantMq.get());
        }
        if (step == 4) {
            return AjaxResult.success(updateAnswerFromMq.get());
        }
        return AjaxResult.error("参数有误");
    }


    //清理mq 去重表的数据
    @ApiOperation("一键操作 第 2.1 步 的 弹框 点确定的时候 调这个，点取消的时候调用第3 步 这一步不会超时")
    @DeleteMapping("/cleanUpOldData")
    public AjaxResult cleanUpOldData() {
        downLoadAnswerService.truncateMqQc();
        return AjaxResult.success("清除完成");
    }

    //列举出formal answer 中数据为-1 的 但是 mq 中不是-1 的值
    @ApiOperation("一键操作 第 3 步 获取异常列表 这一步可能超时")
    @GetMapping("/listUnAssemblyData")
    public synchronized TableDataInfo listUnAssemblyData() {
        return getDataTable(downLoadAnswerService.listUnAssemblyData());
    }

    //合并数据更新结果
    @ApiOperation("一键操作  第 4 步 修改数据")
    @GetMapping("/updateAnswerFromMq")
    public AjaxResult updateAnswerFromMq() {

        if (updateAnswerFromMq.get()) {
            try {
                updateAnswerFromMq.set(false);
                return toAjax(downLoadAnswerService.updateAnswerFromMq());
            } finally {
                updateAnswerFromMq.set(true);
                //更新roadMap
                downLoadAnswerService.updateMergeRoadMap();
            }
        } else {
            return AjaxResult.error("有人正在执行操作请等待");
        }
    }


    @ApiOperation("日志下载")
    @GetMapping("/downLoadLog/{testSession}")
    public AjaxResult downLoadLog(@PathVariable("testSession") Integer testSession) {

        if (canDownLoadLog.get()) {
            try {
                canDownLoadLog.set(false);
                int res = downLoadAnswerService.downLoadLog(testSession);
                if (res == -1) {
                    return AjaxResult.error("已经下载过了");
                }
                return AjaxResult.success("下载完成");
            } finally {
                canDownLoadLog.set(true);
            }
        } else {
            return AjaxResult.error("有人正在执行操作请等待");
        }
    }

    @ApiOperation("获取日志下载的进度")
    @GetMapping("/logProgress")
    public AjaxResult logProgress() {
        String progress = downLoadAnswerService.logProgress();
        return AjaxResult.success(progress);
    }

}
